<template>
  <div class="login">
    <div class="login-bg">
      <div class="login-form">
        <van-form @submit="onSubmit">
          <van-field
            class="login-form-input"
            v-model="form.name"
            size="large"
            name="学生姓名"
            label=""
            placeholder="学生姓名"
          />
          <van-field
            class="login-form-input"
            v-model="form.phone"
            name="手机号"
            size="large"
            label=""
            placeholder="手机号"
          />
          <van-field
            class="login-form-input"
            v-model="form.sms"
            size="large"
            center
            clearable
            label=""
            placeholder="验证码"
          >
            <template #button>
              <div
                class="login-btn"
                :class="btnTxt != '获取验证码' ? 'login-unDisable' : ''"
                @click="getCode"
              >
                {{ btnTxt }}
              </div>
            </template>
          </van-field>
          <div class="login-sub">
            <van-button
              :disabled="!(form.phone && form.name && form.sms)"
              round
              block
              type="info"
              native-type="submit"
              >开始测试</van-button
            >
          </div>
        </van-form>
        <div class="login-attition">
          <p class="login-attition-tit">注意：</p>
          <p class="login-attition-line">1.请务必填写姓名</p>
          <p class="login-attition-line">
            2.请不要在测试过程中查看书、笔记等资料
          </p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  wxShare,
  getUnievaluationQuestiont,
  loginPhone,
  getWechat,
  verificationCode,
} from "@/server/api.js";

import { GetUrlParame } from "@/utils/utils";
import { mapGetters } from "vuex";
export default {
  name: "home",
  components: {},
  data() {
    let that = this;
    return {
      form: {
        phone: "",
        name: "",
        sms: "",
      },
      allBookList: [],
      editionArr: [],
      bookArr: [],
      unitArr: [],
      sheetVisible: false,
      selectChapterId: [],
      cur_param: {},
      btnTxt: "获取验证码",
      time: 0,
      time2: "",
    };
  },
  computed: {
    ...mapGetters(["param", "info"]),
  },
  created() {
    this.cur_param = this.getParam();
    if (this.cur_param.Type && this.cur_param.Type == 998) {
      location.href = `https://www.xiaoguoai.cn/invite/#/home/?inviterType=${this.cur_param.inviterType}&inviterId=${this.cur_param.inviterId}&campusId=${this.cur_param.campusId}&oid=${this.cur_param.oid}`;
      return;
    }
    this.cur_param.code = "3321";
    let newParam = Object.assign({}, this.param, this.cur_param);
    this.$store.dispatch("setParam", newParam);
    this.getWechat();
  },
  mounted() {
    //this.getSubjet();
  },

  methods: {
    timeComputer() {
      let time = 60;
      let that = this;
      this.btnTxt = time;
      this.time2 = setInterval(function() {
        time--;
        if (time < 0) {
          clearInterval(that.time2);
          that.btnTxt = "获取验证码";
          return;
        }
        that.btnTxt = time;
      }, 1000);
    },
    getCode() {
      let btn = this.checkForm(2);
      if (btn && this.btnTxt == "获取验证码") {
        this.timeComputer();
        let param = {
          openId: this.param.wechatId,
          phone: this.form.phone,
        };
        verificationCode(param).then((res) => {
          if (res.code == 200) {
            this.$toast("发送成功");
          } else {
            clearInterval(this.time2);
            this.btnTxt = "获取验证码";
          }
        });
      }
    },
    isPoneAvailable(num) {
      if (!String(num).trim()) {
        this.$toast("请输入手机号");
        return false;
      }
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!myreg.test(String(num))) {
        this.$toast("请输入正确手机号");
        return false;
      } else {
        return true;
      }
    },
    isUserName(name) {
      if (!String(name).trim()) {
        this.$toast("请输入姓名");
        return false;
      }
      var myreg1 = /^[a-zA-Z ]{1,20}$/;
      var myreg2 = /^[\u4e00-\u9fa5]{1,10}$/;
      if (myreg1.test(String(name)) || myreg2.test(String(name))) {
        return true;
      } else {
        this.$toast("请输入正确姓名");
        return false;
      }
    },

    isCode(code) {
      if (!String(code)) {
        this.$toast("请输入验证码");
        return false;
      } else {
        return true;
      }
    },

    checkForm(type) {
      //type为1提交 2 获取验证码
      if (type == 2) {
        if (!this.isPoneAvailable(this.form.phone)) {
          return false;
        } else {
          return true;
        }
      } else {
        if (!this.isUserName(this.form.name)) {
          return false;
        } else if (!this.isPoneAvailable(this.form.phone)) {
          return false;
        } else if (!this.isCode(this.form.sms)) {
          return false;
        } else {
          return true;
        }
      }
    },
    getWechat() {
      let wechatId = this.param.wechatId;
      console.log(`wechatId: ${wechatId}`);
      /*
      getWechat(wechatId).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.info.id = res.data.id;
            this.info.userInfo.realName = res.data.realName;
            this.$store.dispatch("setInfo", this.info);
            this.$router.push({
              path: "/selectItem",
            });
          }
        }
      });
      */
    },
    onSubmit() {
      let btn = this.checkForm(1);
      if (!btn) {
        return;
      }
      let innerParam = {
        wechatId: this.param.wechatId,
        phone: this.form.phone,
        realName: this.form.name,
        code: this.form.sms,
      };
      let newParam = Object.assign({}, this.param, {
        realName: this.form.name,
        phone: this.form.phone,
      });
      this.$store.dispatch("setParam", newParam);
      loginPhone(innerParam).then((res) => {
        if (res.code == 200) {
          this.info.id = res.data;
          this.info.userInfo.realName = innerParam.realName;
          this.$store.dispatch("setInfo", this.info);
          this.$router.push({
            path: "/selectItem",
          });
        } else {
          this.$toast(res.message);
        }
      });
    },
    isWeiXin() {
      //检测环境是否为微信
      let ua = window.navigator.userAgent.toLowerCase();
      return ua.match(/MicroMessenger/i) == "micromessenger";
    },

    getParam() {
      let state = GetUrlParame("state");
      let openId = GetUrlParame("openId");
      let arr = state.split("gs");
      let param = {
        wechatId: openId,
      };
      let paramName = ["inviterId", "inviterType", "campusId", "oid", "Type"];
      arr.map((item) => {
        paramName.map((item2) => {
          let cvt = item.indexOf(item2);
          if (cvt > -1) {
            param[item2] = item.replace(/[^0-9]/gi, "");
          }
        });
      });

      return param;
    },
  },
};
</script>
